package com.tledu.dangjian.core.interceptor;

import com.tledu.dangjian.core.annotion.Auth;
import com.tledu.dangjian.core.constants.CommonConstants;
import com.tledu.dangjian.model.Resource;
import com.tledu.dangjian.model.User;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * @author cyrus
 */
public class AuthInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // hanlder就是Controller和对应method
        HandlerMethod handlerMethod = (HandlerMethod) handler;

        // true代表如果没有session就会创建一个session，false没有session就会返回null
        HttpSession session = request.getSession(true);
        User user = (User) session.getAttribute(CommonConstants.LOGIN_USER_SESSION_KEY);
        if (user == null) {
            // 代表没有登录
            response.sendRedirect(request.getContextPath() + "/login");
            // 终止后续请求
            return false;
        }

        Method method = handlerMethod.getMethod();
        Object obj = handlerMethod.getBean();
        // 进行进一步的校验
        List<Resource> resourceList = (List<Resource>) session.getAttribute(CommonConstants.LOGIN_RESOURCE_SESSION_KEY);
        // 怎么获取到注解
        Auth auth = method.getAnnotation(Auth.class);
        if (auth != null) {
            // 有限制的
            String perm = auth.auth();
            for (Resource resource : resourceList) {
                if (resource.getPerm().equals(perm)) {
                    // 有权限的
                    return super.preHandle(request, response, handler);
                }
            }
            // 这个时候没有权限
            response.sendRedirect(request.getContextPath() + "/401");
            return false;
        }
        return super.preHandle(request, response, handler);
    }
}
